package dao;

import java.io.Serializable;
import java.util.List;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import modelo.Cita;
import modelo.Estadocita;
import modelo.Interesado;
import modelo.Salon;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import util.HibernateUtil;

public class SalonWebDao implements Serializable {

	
	private static final long serialVersionUID = 417208331437551763L;
	private Session session;
	SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

	public SalonWebDao() {
		super();
	}

	public SalonWebDao(Session session, SessionFactory sessionFactory) {
		super();
		this.session = session;
	}

	public List<Salon> obtenerSalon() {
		session = sessionFactory.openSession();

		Query query = session.createQuery("SELECT s FROM Salon s");
		List<Salon> s = query.list();

		session.close();

		return s;
	}
		
		public Salon obtenerSalonById(int id) {
		session = sessionFactory.openSession();
		Query query = session.createQuery("from Salon where IdSalon = :id ");
		query.setParameter("id", id);

		List<?> list = query.list();

		Salon s = (Salon) list.get(0);
		return s;
	}

		public void registrarCita(int idSalon) {
	
			session = sessionFactory.openSession();
			session.beginTransaction();
			
			Cita cita = new Cita();
			Estadocita estado = new Estadocita();
			Salon salon = new Salon();
			estado.setId(1);
			salon.setIdSalon(idSalon);
			cita.setEstadocita(estado);
			cita.setSalon(salon);
            FacesContext context = javax.faces.context.FacesContext.getCurrentInstance();
            HttpSession sessionActual = (HttpSession) context.getExternalContext().getSession(false);
            Integer nB = Integer.parseInt(sessionActual.getAttribute("persona").toString());
            
            try {
            
//        session=sessionFactory.openSession();

			Criteria cr = session.createCriteria(Interesado.class);
			cr.add(Restrictions.eq("persona.idPersona", nB));
			List<Interesado> ca= cr.list();
			//session.close();
			
			cita.setInteresado(ca.get(0));

			session.save(cita);
			session.getTransaction().commit();

    		} catch (Exception e) {
    			e.getCause();
    			e.getMessage();
    			session.getTransaction().rollback();
    		} finally {
    			session.close();
    		}
		}
		
	

		
		
		
}